package com.stella.comeon.services;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Slf4j
@Service
public class PdfProcessingService {

    //    private static final String INPUT_ROOT = "E:\\BaiduNetdiskDownload\\牛津树\\牛津树1-14阶段PDF+音频"; // e.g., "/path/to/stage-01"
    private static final String INPUT_ROOT = "E:\\BaiduNetdiskDownload\\牛津树\\牛津树1-14阶段PDF+音频"; // e.g., "/path/to/stage-01"
    private static final String OUTPUT_ROOT = INPUT_ROOT + "\\images";

    @Value("${file.pdfbox.font-cache:#{null}}")
    void setPdfBoxFontCache(String cacheDir) {
        if (cacheDir != null) {
            System.setProperty("pdfbox.fontcache", cacheDir);
        }
    }

    public void processStages() throws IOException {
        for (int i = 1; i <= 14; i++) {
            String stageNum = String.format("%02d", i);
            final Integer stageIntNum = i;
            final String stageName = "stage-" + stageNum;
            Path stageDir = Paths.get(INPUT_ROOT, stageName, "/PDF");
            log.info("文件夹路径{}", stageDir);
            if (!Files.exists(stageDir)) {
                continue;
            }

            Files.list(stageDir)
                    .filter(p -> p.toString().toLowerCase().endsWith(".pdf"))
                    .forEach(pdfPath -> {
                        try {
                            processPdfFile(pdfPath, stageName, stageIntNum);
                        } catch (IOException e) {
                            log.warn("处理文件失败: " + pdfPath + " | 错误: " + e.getMessage());
                        }
                    });
        }
    }

    private void processPdfFile(Path pdfPath, String stageName, Integer stageNum) throws IOException {
        String originalFileName = pdfPath.getFileName().toString();
        log.info("读取原文件路径[ {} ]", originalFileName);
        // 解码 HTML 实体：&#39; -> '
        String decodedName = StringEscapeUtils.unescapeHtml4(originalFileName).toLowerCase();
        log.info("反转义文件路径[ {} ]", originalFileName);
        Path targetPdfPath = pdfPath.getParent().resolve(decodedName);

        // 如果文件名不同，则重命名
        if (!originalFileName.equals(decodedName)) {
            log.info("存在转义，开始重命名文件[ {} ]", decodedName);
            Files.move(pdfPath, targetPdfPath, StandardCopyOption.REPLACE_EXISTING);
        }

        // 提取书名（不含扩展名）
        String bookName = formatBookName(decodedName);
        Path outputBookDir = Paths.get(OUTPUT_ROOT + "\\" + stageName + "\\", bookName);
        BookService bookService = SpringUtil.getBean(BookService.class);

        String relativeSrcPath = targetPdfPath.toString().substring(INPUT_ROOT.length()).replaceAll("\\\\","/");
        String relativeDistPath = outputBookDir.toString().substring(INPUT_ROOT.length()).replaceAll("\\\\","/");
        bookService.saveBook(stageNum, relativeSrcPath, relativeDistPath, bookName, decodedName.split("\\.")[0]);
        // 创建输出目录

        // convertPdfToImgs(targetPdfPath, outputBookDir);
    }

    /**
     * 读取pdf转换为图片
     *
     * @param targetPdfPath
     * @param outputBookDir
     * @throws IOException
     */
    private static void convertPdfToImgs(Path targetPdfPath, Path outputBookDir) throws IOException {
        Files.createDirectories(outputBookDir);

        // 使用 PDFBox 加载 PDF 并转换为 PNG
        try (PDDocument document = PDDocument.load(targetPdfPath.toFile())) {
            PDFRenderer renderer = new PDFRenderer(document);
            int pageCount = document.getNumberOfPages();

            log.info("{} 转换pdf内容，共{}页", outputBookDir, pageCount);
            for (int pageNum = 0; pageNum < pageCount; pageNum++) {
                try {
                    // 150 DPI
                    BufferedImage image = renderer.renderImageWithDPI(pageNum, 150);
                    String pngFileName = String.format("%03d.png", pageNum);
                    Path pngFile = outputBookDir.resolve(pngFileName);
                    log.info("pdf转img文件输出: {}/{}", outputBookDir, pngFileName);
                    ImageIO.write(image, "PNG", pngFile.toFile());
                } catch (Exception e) {
                    log.warn("{}页pdf转图片失败{}", e.getMessage(), e);

                }
            }
        }
    }

    private String formatBookName(String fileName) {
        // 先移除扩展名
        String nameWithoutExtension = removeExtension(fileName);
        // 去除多余空格，将多个空格替换为单个空格
        String cleanedName = nameWithoutExtension.replaceAll("\\s+", " ").trim();

        // 按空格分割字符串
        String[] words = cleanedName.split(" ");
        StringBuilder formattedName = new StringBuilder();

        for (String word : words) {
            if (!word.isEmpty()) {
                // 首字母大写，其余字母小写
                formattedName.append(Character.toUpperCase(word.charAt(0)))
                        .append(word.substring(1).toLowerCase());
            }
        }

        return formattedName.toString();
    }

    private String removeExtension(String fileName) {
        int lastDotIndex = fileName.lastIndexOf('.');
        return lastDotIndex > 0 ? fileName.substring(0, lastDotIndex) : fileName;
    }

    public static void main(String[] args) {
        try {
            new PdfProcessingService().processStages();
        } catch (IOException e) {
            log.warn("转换文件出错:{}", e.getMessage(), e);
        }

    }
}